<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--机构数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="unitName"
            placeholder="请输入规格名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="unitsKeyList"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            @node-click="handleNodeClick"
            :render-content="renderContent"
          />
        </div>
      </el-col>
      <!--规格值-->
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="规格值" prop="unitValue">
          <el-input
            v-model="queryParams.unitValue"
            placeholder="请输入规格值"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-col :span="20" :xs="24">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['goods:unitsKey:add']"
            >新增规格</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              @click="handleUpdateKey"
              v-hasPermi="['goods:unitsKey:edit']"
            >{{ edit?'取消编辑':'编辑规格' }}</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleValueAdd"
              v-hasPermi="['goods:unitsValue:add']"
            >新增规格值</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleValueDelete"
              v-hasPermi="['goods:unitsKey:remove']"
            >删除规格值</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getUnitsKeyList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="unitsValueList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="规格名称" align="center" prop="unitName" />
          <el-table-column label="规格值" align="center" prop="unitValue" />
          <el-table-column label="排序号" align="center" prop="sort" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleValueUpdate(scope.row)"
                v-hasPermi="['goods:unitsKey:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleValueDelete(scope.row)"
                v-hasPermi="['goods:unitsKey:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getUnitsKeyList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改商品规格对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="规格名称" prop="unitName">
          <el-input v-model="form.unitName" placeholder="请输入规格" />
        </el-form-item>
        <el-form-item label="排序号" prop="sort">
          <el-input-number style="width: 100%" :min="1" v-model="form.sort"  />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改商品规格值对话框 -->
    <el-dialog :title="title" :visible.sync="valueOpen" width="500px" append-to-body>
      <el-form ref="valueForm" :model="valueForm" :rules="rules" label-width="80px">
        <el-form-item label="商品规格" prop="unitId">
          <el-select v-model="valueForm.unitId" style="width: 100%"  placeholder="请选择">
            <el-option
              v-for="item in unitsKeyList"
              :key="item.id"
              :label="item.unitName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="规格值" prop="unitValue">
          <el-input v-model="valueForm.unitValue" placeholder="请输入规格值" />
        </el-form-item>
        <el-form-item label="排序号" prop="sort">
          <el-input-number :min="1" v-model="valueForm.sort" style="width: 100%;" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitValueForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listUnitsKey, getUnitsKey, delUnitsKey, addUnitsKey, updateUnitsKey } from "@/api/goods/unitsKey";
import {addUnitsValue, delUnitsValue, getUnitsValue, listUnitsValue, updateUnitsValue} from "@/api/goods/unitsValue";

export default {
  name: "UnitsKey",
  data() {
    return {
      // 遮罩层
      loading: false,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 编辑规格
      edit: false ,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      unitName:'',
      // 商品规格表格数据
      unitsKeyList: [],
      // 商品规格值表格数据
      unitsValueList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      valueOpen:false,
      // 查询参数
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        unitId: null,
        unitValue: null
      },
      defaultProps: {
        children: "children",
        label: "unitName"
      },
      // 表单参数
      form: {},
      valueForm:{},
      // 表单校验
      rules: {
        unitName: [
          { required: true, message: "规格不能为空", trigger: "blur" },
          { max: 20, message: '规格名称长度不能超过20个字符', trigger: 'blur' }
        ],
        unitId: [
          { required: true, message: "规格不能为空", trigger: ["blur","change"] },
        ],
        unitValue: [
          { required: true, message: "规格值不能为空", trigger: "blur" },
          { max: 20, message: '规格值长度不能超过20个字符', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: "排序号不能为空", trigger: "blur" },
          { pattern: /^[0-9]\d*$/, message: "排序号必须为正整数", trigger: "blur" },
        ]
      }
    };
  },
  watch: {
    // 根据名称筛选机构树
    unitName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getUnitsKeyList();
    this.getUnitsValueList();
  },
  methods: {
    /** 查询商品规格列表 */
    getUnitsKeyList() {
      listUnitsKey().then(response => {
        this.unitsKeyList = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.unitName.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.unitId = data.id;
      this.getUnitsValueList();
    },
    renderContent(h, { node, data, store }) {
      if(this.edit){
        return (
          <span class="custom-tree-node" style="width:100%;font-size:14px">
            <span>{node.label}</span>
            <span style="float:right" >
              <el-button  size="mini" type="text" on-click={() => this.handleUpdate(data)}  icon="el-icon-edit" ></el-button>
              <el-button  size="mini" type="text" on-click={() => this.handleDelete(data)} icon="el-icon-delete"></el-button>
            </span>
          </span>);
      }else {
        return (
          <span class="custom-tree-node" style="width:100%;font-size:14px">
            <span>{node.label}</span>
          </span>);
      }

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.valueOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        extAppid: null,
        unitName: null,
        sort: null
      };
      this.resetForm("form");
      this.valueForm = {
        id: null,
        unitId: null,
        unitValue: null,
        sort: null
      };
      this.resetForm("valueForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.queryParams.unitId = null;
      this.getUnitsValueList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品规格";
    },
    handleUpdateKey(){
      this.edit=!this.edit;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getUnitsKey(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商品规格";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateUnitsKey(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getUnitsKeyList();
            });
          } else {
            addUnitsKey(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getUnitsKeyList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id;
      this.$confirm('是否确认删除商品规格"' + row.unitName + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delUnitsKey(ids);
        }).then(() => {
          this.getUnitsKeyList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    getUnitsValueList() {
      this.loading = true;
      listUnitsValue(this.queryParams).then(response => {
        this.unitsValueList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleValueAdd() {
      this.reset();
      this.valueForm.unitId = this.queryParams.unitId;
      this.valueOpen = true;
      this.title = "添加商品规格值";
    },
    /** 修改按钮操作 */
    handleValueUpdate(row) {
      this.reset();
      getUnitsValue(row.id).then(response => {
        this.valueForm = response.data;
        this.valueOpen = true;
        this.title = "修改商品规格值";
      });
    },
    /** 提交按钮 */
    submitValueForm() {
      this.$refs["valueForm"].validate(valid => {
        if (valid) {
          if (this.valueForm.id != null) {
            updateUnitsValue(this.valueForm).then(response => {
              this.msgSuccess("修改成功");
              this.valueOpen = false;
              this.getUnitsValueList();
            });
          } else {
            addUnitsValue(this.valueForm).then(response => {
              this.msgSuccess("新增成功");
              this.valueOpen = false;
              this.getUnitsValueList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleValueDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除选中的商品规格值吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delUnitsValue(ids);
      }).then(() => {
        this.getUnitsValueList();
        this.msgSuccess("删除成功");
      }).catch(() => {});
    },
  }
};
</script>
